package servlet.lifecycle;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class CounterServlet
 */
public class CounterServlet extends HttpServlet {
	private String file = null;
	private int counter;//서블릿 객체는 하나만 만들어지기 때문에
	
	public void init(){
		
		file = getInitParameter("path");
		//매우 중요! ServletConfig는 init() 이후에서부터 사용가능
		//파일에 저장된 카운터 값을 읽어서 counter변수에 할당
		FileInputStream fis = null;
		DataInputStream dis = null;
		
		try{
			fis = new FileInputStream(file);
			dis = new DataInputStream(fis);
			counter = dis.readInt();
			
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(dis != null) try{dis.close();}catch(IOException e){}
            if(fis != null) try{fis.close();}catch(IOException e){}
		}
	}
	public void destroy(){
		//counter 변수의 값을 file에 출력
		FileOutputStream fos = null;
		DataOutputStream dos = null;
		
		try {
			fos = new FileOutputStream(file);
			dos = new DataOutputStream(fos);
			dos.writeInt(counter);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
            if(fos != null) try{fos.close();}catch(IOException e){}
		}
	}
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	 
		response.setContentType("text/html; charset=utf-8");
		PrintWriter out = response.getWriter();
		out.println("<html><head><title>카운터</title></heal><body>");
		
		out.println("당신은 "+ ++counter +"번째 방문자입니다.");
		out.println("<p><a href='index.html'>index.html로 이동</a></p>");
		out.println("</body></html>");

	}

}
